import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import {
  addDept,
  deleteDept,
  type Dept,
  getDeptList,
  updateDept
} from "@/api/dept";
import { usePublicHooks } from "@/views/hooks";
import { addDialog } from "@/components/ReDialog/index";
import { reactive, ref, onMounted, h } from "vue";

export function useDept() {
  const form = reactive<Dept>({
    name: null,
    state: null
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();

  const columns: TableColumnList = [
    {
      label: "部门名称",
      prop: "name",
      width: 180,
      align: "left"
    },
    {
      label: "排序",
      prop: "sort",
      minWidth: 70
    },
    {
      label: "状态",
      prop: "state",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.state)}>
          {row.state ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      minWidth: 200,
      prop: "created"
    },
    {
      label: "备注",
      prop: "description",
      minWidth: 320
    },
    {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ];

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function onSearch() {
    loading.value = true;
    getDeptList(form)
      .then(data => {
        dataList.value = handleTree(data); // 处理成树结构
      })
      .catch(err => {
        message(`部门查询失败:${err.message}`, {
          type: "error"
        });
      })
      .finally(() => {
        setTimeout(() => {
          loading.value = false;
        }, 500);
      });
  }

  function openDialog(title = "新增", row?: Dept) {
    addDialog({
      title: `${title}部门`,
      props: {
        formInline: {
          id: row?.id ?? "",
          parentId: row?.parentId ?? 0,
          name: row?.name ?? "",
          leaderId: row?.leaderId ?? "",
          sort: row?.sort ?? 1,
          state: row?.state ?? true,
          description: row?.description ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as Dept;
        function add() {
          addDept(curData)
            .then(() => {
              message("部门新增成功", {
                type: "success"
              });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`部门新增失败:${err}`, {
                type: "error"
              });
            });
        }
        function update() {
          updateDept(curData)
            .then(() => {
              message("部门更新成功", { type: "success" });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`部门更新失败:${err}`, { type: "error" });
            });
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              add();
            } else {
              // 实际开发先调用编辑接口，再进行下面操作
              update();
            }
          }
        });
      }
    });
  }

  function handleDelete(row) {
    if (!row.isLeaf) {
      message("请先删除所有子部门后再删除上级部门", { type: "warning" });
      return;
    }
    deleteDept(row.id)
      .then(() => {
        message("部门删除成功", { type: "success" });
        onSearch();
      })
      .catch(err => {
        message(`部门删除失败:${err}`, { type: "error" });
      });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、编辑部门 */
    openDialog,
    /** 删除部门 */
    handleDelete
  };
}
